package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.datatransfer.FlavorMap;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServicelmpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;
@Autowired
    private DishFlavorMapper dishFlavorMapper;
@Autowired
private CategoryMapper categoryMapper;
@Autowired
private SetmealMapper    setmealMapper;


    @Override
    @Transactional // 事务注解涉及到多个表，需要开启事务，防止数据不一致（要么全部成功，要么全部失败）
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //菜品表插入一条数据
        dishMapper.insert1(dish);
        //获取到菜品id
        Long dishId = dish.getId();
        //设置菜品id到口味表中
        //口味表插入多条数据
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors!= null && dishFlavors.size() > 0) {
                for(DishFlavor dishFlavor : dishFlavors) {
                    dishFlavor.setDishId(dishId);

                    dishFlavorMapper.insert1(dishFlavor);
                }

        }
    }

    @Override
    public PageResult page1(DishPageQueryDTO dishPageQueryDTO) {
        // 采用mybatis-plus分页插件
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();

        // 如果提供了名称，添加模糊查询条件
        if (dishPageQueryDTO.getName() != null && !dishPageQueryDTO.getName().isEmpty()) {
            queryWrapper.like("name", dishPageQueryDTO.getName());
        }

        // 如果提供了类别ID，添加类别查询条件
        if (dishPageQueryDTO.getCategoryId() != null) {
            queryWrapper.eq("category_id", dishPageQueryDTO.getCategoryId());
        }

        // 如果提供了状态，添加状态查询条件
        if (dishPageQueryDTO.getStatus() != null) {
            queryWrapper.eq("status", dishPageQueryDTO.getStatus());
        }
        //设置降序
        queryWrapper.orderByDesc("create_time").orderByDesc("update_time");

        // 设置分页参数
        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        // 执行分页查询
        Page<Dish> pageResult = dishMapper.selectPage(page, queryWrapper);

        log.info("总记录数: " + pageResult.getTotal());
        List<DishVO> records = new ArrayList<>();
        for (Dish dish : pageResult.getRecords()) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setCategoryName(categoryMapper.selectById(dish.getCategoryId()).getName());
            records.add(dishVO);
        }
        PageResult pageResult1 = new PageResult();
        pageResult1.setRecords(records);
        pageResult1.setTotal(pageResult.getTotal());
        return pageResult1;
    }

    @Override
    @Transactional // 事务注解涉及到多个表，需要开启事务，防止数据不一致（要么全部成功，要么全部失败）
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
           Dish dish =  dishMapper.selectById(id);
          if(dish.getStatus() == StatusConstant.ENABLE) {
              //处于启售状态的菜品不能删除
              throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE); //抛出异常
          }
        }
        //当前菜品被套餐关联不能删除
       QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
       queryWrapper.in("id", ids);
        List<Setmeal> setmeals = setmealMapper.selectBatchIds(ids);
        if(setmeals!= null && setmeals.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL); //抛出异常
        }
        //删除菜品
            dishMapper.deleteBatchIds(ids);

        //删除菜品口味
        dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().in("dish_id", ids));
    }

    //根据id修改菜品和口味信息
    @Override
    @Transactional // 事务注解涉及到多个表，需要开启事务，防止数据不一致（要么全部成功，要么全部失败）
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        //删除原有口味信息
        dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().eq("dish_id", dish.getId()));
        //插入新的口味信息
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if(dishFlavors != null && dishFlavors.size() > 0) {
            for(DishFlavor dishFlavor : dishFlavors) {
                dishFlavor.setDishId(dish.getId());
                dishFlavorMapper.insert1(dishFlavor);
            }
        }
    }
  //根据id修改菜品状态
    @Override
    public void updateStatus(String status, Long id) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Dish dish = dishMapper.selectOne(queryWrapper);
        dish.setStatus(Integer.valueOf(status));
        dishMapper.updateById(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", StatusConstant.ENABLE);
        queryWrapper.eq("category_id", dish.getCategoryId());
        //排序
        queryWrapper.orderByDesc("create_time").orderByDesc("update_time");
        List<Dish> dishList = dishMapper.selectList(queryWrapper); //根据分类id查询出符合条件的菜品()

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            QueryWrapper<DishFlavor> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dish_id", d.getId());
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectList(queryWrapper1);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
